package com.zh.harmony.mvvmharmony;

import com.ryan.ohos.extension.widget.viewpager.PagerAdapter;
import com.zh.harmony.fragment.Fragment;
import com.zh.harmony.fragment.FragmentManager;
import com.zh.harmony.fragment.FragmentTransaction;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;

/**
 * Fragment配合ViewPager使用时使用
 */
public abstract class FragmentPagerAdapter extends PagerAdapter {
    private final FragmentManager mFragmentManager;
    private FragmentTransaction mCurTransaction = null;

    public FragmentPagerAdapter(FragmentManager fm) {
        this.mFragmentManager = fm;
    }

    /**
     * Return the Fragment associated with a specified position.
     */
    public abstract Fragment getItem(int position);

    @Override
    public void startUpdate(ComponentContainer container) {
        if (container.getId() == Component.ID_DEFAULT) {
            throw new IllegalStateException("ViewPager with adapter " + this
                    + " requires a view id");
        }
    }

    @Override
    public Object instantiateItem(ComponentContainer container, int position) {
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }

        final long itemId = getItemId(position);

        // Do we already have this fragment?
        String name = makeFragmentName(container.getId(), itemId);
        Fragment fragment = mFragmentManager.findFragmentByTag(name);
        if (fragment != null) {
            mCurTransaction.attach(fragment);
        } else {
            fragment = getItem(position);
            mCurTransaction.add(container.getId(), fragment,
                    makeFragmentName(container.getId(), itemId));
        }
        return fragment;
    }

    @Override
    public void destroyItem(ComponentContainer container, int position, Object object) {
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }
        mCurTransaction.remove((Fragment) object);
    }

    @Override
    public void finishUpdate(ComponentContainer container) {
        if (mCurTransaction != null) {
            mCurTransaction.commit();
            mCurTransaction = null;
        }
    }

    @Override
    public boolean isViewFromObject(Component view, Object object) {
        return ((Fragment) object).getView() == view;
    }

    /**
     * Return a unique identifier for the item at the given position.
     *
     * <p>The default implementation returns the given position.
     * Subclasses should override this method if the positions of items can change.</p>
     *
     * @param position Position within this adapter
     * @return Unique identifier for the item at position
     */
    public long getItemId(int position) {
        return position;
    }

    private static String makeFragmentName(int viewId, long id) {
        return "android:switcher:" + viewId + ":" + id;
    }
}